package controller

import (
	"admin/contrib/session"
	"admin/contrib/validator"
	"admin/model"
	"common/helper"
	"encoding/json"
	"github.com/valyala/fasthttp"
)

type AppUpgradeController struct{}

var (
	apps = map[string]bool{
		"ios":     true,
		"android": true,
	}
)

// 修改
func (that *AppUpgradeController) Update(ctx *fasthttp.RequestCtx) {

	var param model.AppUpgrade

	b := ctx.PostBody()
	err := json.Unmarshal(b, &param)
	if err != nil {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	if _, ok := apps[param.Platform]; !ok {
		helper.RetData(ctx, false, helper.DeviceErr)
		return
	}

	if len(param.Content) > 255 {
		helper.RetData(ctx, false, helper.ContentLengthErr)
		return
	}

	if !validator.CheckUrl(param.URL) {
		helper.RetData(ctx, false, helper.URLErr)
		return
	}

	admin := session.AdminGet(ctx)

	param.Content = model.FilterInjection(param.Content)
	param.UpdatedAt = uint32(ctx.Time().Unix())
	param.UpdatedName = admin["name"]
	param.UpdatedUid = admin["id"]

	err = model.AppUpgradeUpdate(param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

// 版本管理列表
func (that *AppUpgradeController) List(ctx *fasthttp.RequestCtx) {

	data, err := model.AppUpgradeList()
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}
